{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#  Dictionaries\n",
    "\n",
    "## 1 Dictionary: Mapping Types\n",
    "The useful data type built into Python is the **dictionary**\n",
    "\n",
    "Unlike sequences, which are indexed by a range of numbers, dictionaries are `indexed by keys`, which can be any immutable type; `strings` and `numbers` can always be keys.\n",
    "\n",
    "In mathematical language, a dictionary represents a `mapping` from `keys` to `values`, so you can also say that each key “maps to” a value. \n",
    "\n",
    "Literals of type dict are enclosed in  <b style=\"color:blue\">curly braces  {}  </b>, \n",
    "\n",
    "Think of a dictionary as a set of <b style=\"color:blue\">key:value</b> pairs.\n",
    "```python\n",
    "'Jan':1\n",
    "1:'Jan'\n",
    "```\n",
    "\n",
    "and each element is written as a `key` followed by <b style=\"color:blue\">a colon :</b> followed by a `value`. \n",
    "For example, the code,"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    }
   ],
   "source": [
    "monthNumbers= {'Jan':1}\n",
    "print(monthNumbers['Jan'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Jan\n"
     ]
    }
   ],
   "source": [
    "monthString= {1:'Jan'}\n",
    "print(monthString[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**The `entries` in a dict `cannot` be accessed with an `index`.**\n",
    "\n",
    "`monthString[1]` unambiguously refers to the entry with the **key 1**: `1:'Jan'` "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The Mar is the 3 month \n",
      "\n"
     ]
    }
   ],
   "source": [
    "monthNumbers = {'Jan':1, 'Feb':2, 'Mar':3,\n",
    "                 1:'Jan', 2:'Feb', 3:'Mar',}\n",
    "  \n",
    "# The entries in a dict are unordered and cannot be accessed with an index\n",
    "# get value from key\n",
    "\n",
    "print('The Mar is the', format(monthNumbers['Mar']),'month \\n')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The third month is Mar \n",
      "\n"
     ]
    }
   ],
   "source": [
    "print('The third month is ' + monthNumbers[3],'\\n')  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Mar and Jan are 2 months apart\n"
     ]
    }
   ],
   "source": [
    "dist = monthNumbers['Mar'] - monthNumbers['Jan'] \n",
    "print('Mar and Jan are', dist, 'months apart')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "<b style=\"color:blue\">Keys</b> can be values of <b>any immutable type</b>.\n",
    "\n",
    "\n",
    "\n",
    ">Python3.7: The `insertion-order preservation` nature of `dict` objects is now an official part of the Python language spec."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2 Dictionaries are  <font color=\"blue\">mutable.</font>\n",
    "\n",
    "Like lists, **dictionaries are mutable**."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.1 add an entry to a dictionary \n",
    "\n",
    "We can add an entry by writing\n",
    "\n",
    "```python\n",
    "monthNumbers['Apr'] = 4\n",
    "```\n",
    "**add elements(key:value)** to a dictionary by **assigning a value `6`to an `unused` key `'June'`('June':)**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [],
   "source": [
    "monthNumbers['Apr'] = 4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Jan': 1, 'Feb': 2, 'Mar': 3, 1: 'Jan', 2: 'Feb', 3: 'Mar', 'Apr': 4}"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "monthNumbers"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.3  `change` an entry by writing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Jan': 1, 'Feb': 2, 'Mar': 3, 1: 'Jan', 2: 'Feb', 3: 'Mar', 'Apr': '04'}"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "monthNumbers['Apr'] = '04'\n",
    "monthNumbers"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3 Iterate over the entries in a dictionary\n",
    "\n",
    " <b style=\"color:blue\">for</b> statement can be used to `iterate` over the entries in `a dictionary`. \n",
    "\n",
    "```python\n",
    "for <item> in <a dictionary>\n",
    "```\n",
    "\n",
    "However, the `value` assigned to the iteration variable is a <b style=\"color:blue\">key</b>, not a `key/value` pair.\n",
    "\n",
    "For example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Jan\n",
      "Feb\n",
      "Mar\n",
      "1\n",
      "2\n",
      "3\n",
      "['Jan', 'Feb', 'Mar', 1, 2, 3]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "list"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "monthNumbers = {'Jan':1, 'Feb':2, 'Mar':3,\n",
    "                1:'Jan', 2:'Feb', 3:'Mar'}\n",
    "keys = []\n",
    "for e in monthNumbers:\n",
    "    print(e)\n",
    "    keys.append(e) # the value s a key， not a key/value pair.\n",
    "\n",
    "print(keys)\n",
    "type(keys)\n",
    "\n",
    "# There is a error in MIT book:'<' not supported between instances of 'int' and 'str'\n",
    "# keys.sort()\n",
    "# print(keys)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4 Key & Hashing\n",
    "\n",
    "In Dictionary, the built-in `Mapping` implementation is quite **fast**. \n",
    "\n",
    "It uses a technique called **[hashing(散列/哈希)](https://en.wikipedia.org/wiki/Hash_table)**, to do the lookup in time that is nearly `independent` of the `size` of the dictionary.\n",
    "\n",
    "<b style=\"color:blue\">Dictionary is a hash table(散列/哈希表)</b>\n",
    "\n",
    ">A hash table (hash map) is a data structure that can **map** `keys` to `values`. A hash table uses `a hash function` to compute an `index`, also called `a hash code`, into `an array of buckets(桶) or slots(槽）`, from which the desired value can be found\n",
    "\n",
    ">```python\n",
    ">index=hash_function(key) // the location of value in the table\n",
    ">```\n",
    ">散列表/哈希表(Hash table)是根据关键字(Key)直接访问表中记录的数据结构。它通过把关键字映射到表中一个位置来访问记录，以加快查找的速度。这个>`映射函数`叫`散列/哈希函数`，`存放记录的数组`叫做`散列表`。\n",
    ">给定表M，存在函数`f(key)`，对任意给定的关键值key，代入函数后若能得到包含该关键字的记录在表中的地址，则称表M为哈希(Hash）表，函数f(key)为>散列/哈希(Hash) 函数。\n",
    ">\n",
    ">* Reference： [UnitDS-5-Hash_Table](./UnitDS-5-Hash_Table.ipynb)\n",
    "\n",
    "**A key must be an object of a `hashable` type:**\n",
    "\n",
    "Not all types of of objects is a `hashable` type and can be used as keys.\n",
    "\n",
    "*  the built-in **immutable** types are **hashable** \n",
    " \n",
    "*  the built-in **mutable** types are not hashable.\n",
    "\n",
    "<b style=\"color:blue\">Keys</b> can be values of any <b style=\"color:blue\">immutable type</b>.\n",
    "\n",
    "* `Strings` and `numbers` can always be keys. \n",
    "\n",
    "* `Tuples` can be used as keys if they `contain only` strings, numbers, or tuples;\n",
    "\n",
    "The `most common` data type of `key` is **string** : `dictionary = {\"key1”: value1, “key2”: value2}`\n",
    "\n",
    "\n",
    "### Tuples as keys\n",
    " \n",
    "Sometimes,it is convenient to use **tuples as keys**. \n",
    "\n",
    "For example, using a tuple of the form <b style=\"color:blue\">(flightNumber, day)</b> to represent **airline** flights.\n",
    "\n",
    "It would then be easy to use such `tuples as keys` in a dictionary implementing a mapping from **flights** to **arrival times**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Airline_Flight1_Arrival_Time: 2013-05-21 09:50:35 \n",
      "\n",
      "Airline_Flight2_Arrival_Time: 2013-05-21 10:50:35\n"
     ]
    }
   ],
   "source": [
    "# tuple\n",
    "Airline_Flight1=('C1208','2013-05-21')\n",
    "Airline_Flight2=('C1230','2013-05-22')\n",
    " \n",
    "# tuple as dictionary keys.\n",
    "# dict: flights:arrival times\n",
    "Arrival_Times={Airline_Flight1:'2013-05-21 09:50:35',Airline_Flight2:'2013-05-21 10:50:35'}\n",
    "\n",
    "# a mapping from flights to arrival times\n",
    "Airline_Flight1_Arrival_Time=Arrival_Times[Airline_Flight1]\n",
    "print('Airline_Flight1_Arrival_Time:',Airline_Flight1_Arrival_Time,'\\n')\n",
    "\n",
    "Airline_Flight2_Arrival_Time=Arrival_Times[Airline_Flight2]\n",
    "print('Airline_Flight2_Arrival_Time:',Airline_Flight2_Arrival_Time)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5 Dictionary view objects\n",
    "\n",
    "The view objects returned by \n",
    "  \n",
    "* **dict.keys()** :reture is a `dict_keys` object, which is an iterator \n",
    "\n",
    "        \n",
    "* **dict.values()** reture is a `dict_values` object, which is an iterator\n",
    "    \n",
    "    \n",
    "* **dict.items()**:reture is a `dict_items` object, which is an iterator that iterates the `key-value` pairs\n",
    "\n",
    "The view objects can be \n",
    "\n",
    "* `iterated` over using <b style=\"color:blue\">for</b> \n",
    "    \n",
    "* `membership` can be `tested` using <b style=\"color:blue\">in</b> \n",
    "\n",
    "*  easily converted into a `list`, using <b style=\"color:blue\">list</b>\n",
    "\n",
    "They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.\n",
    "\n",
    "### 5.1 dict.keys() \n",
    "\n",
    "The method **keys** returns an object of type `dict_keys`.\n",
    "\n",
    "* The `order` in which the keys appear in the view is `not defined`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_keys(['eggs', 'sausage', 'bacon', 'spam'])"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}\n",
    "keys = dishes.keys() # The order in which the keys appear is not defined.\n",
    "keys"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "eggs\n",
      "sausage\n",
      "bacon\n",
      "spam\n"
     ]
    }
   ],
   "source": [
    "for key in keys:\n",
    "    print(key)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'eggs' in dishes "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['eggs', 'sausage', 'bacon', 'spam']"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list(keys)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.2 dict.values()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_values([2, 1, 1, 500])"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "values = dishes.values()\n",
    "values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "504\n"
     ]
    }
   ],
   "source": [
    "n = 0\n",
    "for val in values:\n",
    "    n += val\n",
    "print(n)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "1 in values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[2, 1, 1, 500]"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list(values)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.3 dict.items()\n",
    "\n",
    "**dict.items()**: Return a new view of the dictionary’s items <strong style=\"color:blue\">(key, value)</strong> pairs  in **tuple** "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_items([('eggs', 2), ('sausage', 1), ('bacon', 1), ('spam', 500)])"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}\n",
    "items = dishes.items()\n",
    "items"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "eggs 2\n",
      "sausage 1\n",
      "bacon 1\n",
      "spam 500\n"
     ]
    }
   ],
   "source": [
    "pairs=[]\n",
    "for (key,value) in dishes.items():\n",
    "    print(key,value)\n",
    "    pairs.append((key,value)) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "('eggs', 2) in items"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(key,value) in monthNumbers.items():\n",
      "[('eggs', 2), ('sausage', 1), ('bacon', 1), ('spam', 500)]\n",
      "('eggs', 2)\n",
      "eggs 2\n"
     ]
    }
   ],
   "source": [
    "pairs=list(dishes.items())\n",
    "print('(key,value) in monthNumbers.items():')\n",
    "print(pairs)\n",
    "print(pairs[0])\n",
    "print(pairs[0][0],pairs[0][1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.4 view objects：dynamic and reflect dict changes\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dict_keys(['eggs', 'sausage', 'bacon', 'spam'])\n",
      "dict_values([2, 1, 1, 500])\n",
      "dict_items([('eggs', 2), ('sausage', 1), ('bacon', 1), ('spam', 500)])\n"
     ]
    }
   ],
   "source": [
    "dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}\n",
    "\n",
    "keys = dishes.keys()\n",
    "values = dishes.values()\n",
    "items=dishes.items()\n",
    "\n",
    "print(keys)\n",
    "print(values)\n",
    "print(items)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**change values**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dict_values([20, 1, 1, 500])\n",
      "dict_items([('eggs', 20), ('sausage', 1), ('bacon', 1), ('spam', 500)])\n"
     ]
    }
   ],
   "source": [
    "dishes['eggs']=20\n",
    "print(values)\n",
    "print(items)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**add a `key:value` pair**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dict_keys(['eggs', 'sausage', 'bacon', 'spam', 'fishes'])\n",
      "dict_values([20, 1, 1, 500, 8])\n",
      "dict_items([('eggs', 20), ('sausage', 1), ('bacon', 1), ('spam', 500), ('fishes', 8)])\n"
     ]
    }
   ],
   "source": [
    "dishes['fishes']=8\n",
    "print(keys)\n",
    "print(values)\n",
    "print(items)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**delete items**\n",
    "\n",
    "* del d[k] :remove key `k` from `d`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dict_keys(['bacon', 'spam', 'fishes'])\n",
      "dict_values([1, 500, 8])\n",
      "dict_items([('bacon', 1), ('spam', 500), ('fishes', 8)])\n"
     ]
    }
   ],
   "source": [
    "del dishes['eggs']\n",
    "del dishes['sausage']\n",
    "print(keys)\n",
    "print(values)\n",
    "print(items)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6 The dictionary methods \n",
    "\n",
    "As with lists, there are many useful methods associated with dictionaries, including some for removing elements. \n",
    "\n",
    "* `d.keys()`： returns a view of the keys in d.\n",
    "\n",
    "* `d.values()`： returns a view of the values in d.\n",
    "\n",
    "* `d.items()`： return a new view of the dictionary’s items <strong style=\"color:blue\">(key, value)</strong> pairs  in **tuple** \n",
    "\n",
    "* `d[k]` ：returns the item in d with key k. Raises KeyError if k is not in d.\n",
    "\n",
    "*  `d[k] = v`： associates the value v with the key k. If there is already a value associated\n",
    "with k, that value is replaced.\n",
    "\n",
    "* `for k in d` iterates over the keys in d.\n",
    "---\n",
    "* `d.update(d1)`: merge the given dictionary d1 into d. Override the value if key exists, else, add new key-value.\n",
    "\n",
    "* `len(d)`： returns the number of items in d.\n",
    "\n",
    "* `d.pop()`: simultaneously returns the value and deletes the key\n",
    "\n",
    "* `d.has_key()`:\n",
    "\n",
    "* `k in d` ：returns True if key k is in d.\n",
    "\n",
    "* `d.get(k, v)`： returns d[k] if k in d, and v otherwise.\n",
    "\n",
    "* `del d[k]`： removes element with key k from d. Raises KeyError if k is not in d.\n",
    "\n",
    "* `d.clear()`: removes all elements from d\n",
    "\n",
    "* `d.copy()`: return a copy of  d"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  6.1 update([other])\n",
    "\n",
    "Update the dictionary with the `key/value` pairs from other, overwriting existing keys. Return None.\n",
    "\n",
    "* `update()` accepts either `another dictionary` object or an `iterable of key/value pairs` (as tuples or other iterables of length two). \n",
    "  \n",
    "* If keyword arguments are specified, the dictionary is then updated with those key/value pairs:\n",
    "\n",
    "The update method changes dicts `in-place`, so any existing keys in the data passed to update will have their old values discarded.\n",
    "\n",
    "You can **merge** one dict into another using the `update` method. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'red': 111, 'blue': 22, 'yellow': 33}"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "d={\"red\":11,\"blue\":22}\n",
    "#  update the Dictionary with another dictionary\n",
    "# the existing key :\"red\":\n",
    "# the new key: \"yellow\"\n",
    "d.update({\"red\":111,\"yellow\":33})\n",
    "d"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'red': 1, 'blue': 2, 'yellow': 33}"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# update the Dictionary with iterable \n",
    "d.update(red=1, blue=2) \n",
    "d"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.2 pop\n",
    "\n",
    "the `pop` method  simultaneously `returns the value` and deletes the key:\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}\n",
    "ret = dishes.pop('eggs') # returns the value simultaneously\n",
    "ret"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'sausage': 1, 'bacon': 1, 'spam': 500}"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dishes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7 Dictionary Comprehension \n",
    "\n",
    "Dictionary comprehension is similar to list comprehension.\n",
    "The general form is \n",
    "```python\n",
    "{key: value for id1, id2 in iterable} \n",
    "```\n",
    "The key difference (other than the use of set braces rather than square braces) is that it uses two values to create each element of the dictionary, and allows (but does not require) the iterable to return two values at a time. \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'I': 1, 'II': 2}"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "r_n={k: v for k, v in (('I', 1), ('II', 2))}\n",
    "r_n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'A': 65, 'B': 66}"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "char_n={chr(n): n for n in (65, 66, 66)}\n",
    "char_n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a': 2, 'b': 4, 'c': 6, 'd': 8, 'e': 10}\n"
     ]
    }
   ],
   "source": [
    "dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}\n",
    "# Double each value in the dictionary\n",
    "double_dict1 = {k:v*2 for (k,v) in dict1.items()}\n",
    "print(double_dict1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "objects = ['blue', 'apple', 'dog']\n",
    "categories = ['color', 'fruit', 'pet']\n",
    "a_dict = {key: value for key, value in zip(categories, objects)}\n",
    "a_dict"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Further Reading \n",
    "\n",
    "**Dictionaries are one of  <b style=\"color:blue\">the great things</b> about Python.**\n",
    "\n",
    "They <b style=\"color:blue\">greatly reduce </b> the difficulty of writing a <b style=\"color:blue\">variety</b> of programs.\n",
    "\n",
    "* [Unit1-5-Files.ipynb](./Unit1-5-Files.ipynb)\n",
    "\n",
    "\n",
    "* [Unit4-2-RefrigerationCycle_OOP](./Unit4-2-RefrigerationCycle_OOP.ipynb)\n",
    "\n",
    "\n",
    "Python Library: 4.10 Mapping Types — dict\n",
    "    \n",
    "  * https://docs.python.org/dev/library/stdtypes.html#mapping-types-dict\n",
    " "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.7"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": false,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "568px",
    "left": "419px",
    "top": "110.98px",
    "width": "333.91px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  },
  "widgets": {
   "state": {},
   "version": "1.1.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
